<template>
	<div class="uploadSimple">
		<van-loading v-if="loading" text-color="#fff" vertical class="customLoading"
			>加载中...</van-loading
		>
		<img ref="image" style="visibility: hidden" :src="captureData" class="camera-preview" />
		<van-uploader
			ref="uploadSimple"
			:after-read="afterRead"
			:show-upload="true"
			:preview-image="false"
		></van-uploader>
		<div class="camera-capture" v-if="isUpload">
			<div class="cancel" @click="cancel">取消</div>
			<div class="sure" @click="submit">确认</div>
		</div>
	</div>
</template>

<script>
import { Uploader } from 'vant';
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
import { get_ocr } from '@/api/PGXT'
export default {
	name: 'upload',
	components: {
		'van-uploader':Uploader
	},
	props:{
		isRefresh:{
			type:Boolean,
			default:true
		}
	},
	data() {
		return {
			loading:false,
			isUpload: false,
			captureData: '',
			cropper: null
		}
	},
	methods: {
		cancel() {
			this.captureData = ''
			this.$emit('updateCom', false)
			this.loading = false
			if(this.isRefresh){
				this.$router.go(0)
			}
		},
		// beforeRead(){
		// 	this.$emit('updateLoading',true)
		// },
		afterRead(val) {
			this.loading = true
			this.$emit('updateCom', true)
			this.imgPreview(val.content)
			// this.$router.push({
			//   path:'/editIdCard'
			// })
		},
		handleImg(dataURL) {
			let self = this
			// self.captureData = dataURL
			// setTimeout(() => {
			// 	self.getImgByCropper()
			// }, 2000)
			let img = new Image()
			img.src = dataURL
			img.onload = function () {
				let newBase64 = self.compress(img)
				//   if (dataURL.length <= 500 * 1024) {
				//   } else {
				//   }
				self.captureData = newBase64
				setTimeout(() => {
					self.getImgByCropper()
				}, 2000)
			}
		},
		compress(img) {
			let canvas = document.createElement('canvas')
			let ctx = canvas.getContext('2d')
			//瓦片canvas
			let tCanvas = document.createElement('canvas')
			let tctx = tCanvas.getContext('2d')
			// let initSize = img.src.length;
			let width = img.width
			let height = img.height
			//如果图片大于四百万像素，计算压缩比并将大小压至400万以下
			let ratio
			if ((ratio = (width * height) / 4000000) > 1) {
				// console.log("大于400万像素");
				ratio = Math.sqrt(ratio)
				width /= ratio
				height /= ratio
			} else {
				ratio = 1
			}
			canvas.width = width
			canvas.height = height
			// 铺底色
			ctx.fillStyle = '#fff'
			ctx.fillRect(0, 0, canvas.width, canvas.height)
			//如果图片像素大于100万则使用瓦片绘制
			let count
			if ((count = (width * height) / 1000000) > 1) {
				count = ~~(Math.sqrt(count) + 1) //计算要分成多少块瓦片
				//            计算每块瓦片的宽和高
				let nw = ~~(width / count)
				let nh = ~~(height / count)
				tCanvas.width = nw
				tCanvas.height = nh
				for (let i = 0; i < count; i++) {
					for (let j = 0; j < count; j++) {
						tctx.drawImage(
							img,
							i * nw * ratio,
							j * nh * ratio,
							nw * ratio,
							nh * ratio,
							0,
							0,
							nw,
							nh
						)
						ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh)
					}
				}
			} else {
				ctx.drawImage(img, 0, 0, width, height)
			}
			//进行最小压缩
			let ndata = canvas.toDataURL('image/jpeg', 0.5)
			tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0
			return ndata
		},
		async getIdCardByOCR(base64) {
			let res = await get_ocr({ ocrType: 'idcard', imgString: base64 })
			if (res.status == 1 && res.id) {
				let obj = {
					idCard: res.id || '',
					name: res.name || '',
					sex: res.sex || '',
					nation: res.nation || '',
					address: res.address || '',
					birthDate: res.birth_date || ''
				}
				this.$emit('sureIdCard',obj)
				this.loading = false
			} else {
				this.loading = false
				this.$toast.fail('身份证信息扫描失败，请重新拍照上传！')
			}
		},
		submit() {
			this.loading = true
			// 获取裁剪后的图片的 base64 格式
			const croppedCanvas = this.cropper.getCroppedCanvas({
				// width: 100,
				// height: 196,
				// left: 600,
				// top: 948
			})
			const croppedBase64 = croppedCanvas.toDataURL()
			this.getIdCardByOCR(croppedBase64)
		},
		getImgByCropper() {
			let self = this
			// 初始化 Cropper.js
			console.log(this.$refs.image)
			// debugger
			this.cropper = new Cropper(this.$refs.image, {
				// aspectRatio: 1 / 1.58, //默认比例
				// autoCropArea: 0.8,
				cropBoxResizable: true,
				cropBoxMovable: true,
				dragMode: 'none',
				ready: function () {
					self.captureData = ''
					self.loading = false
				},
				crop: (event) => {
					console.log(event)
				}
			})
		},
		imgPreview(base64) {
			this.isUpload = true
			// 压缩
			this.handleImg(base64)
			// this.captureData = base64
			// setTimeout(() => {
			//   this.getImgByCropper()
			// }, 1000);
		}
	}
}
</script>
<style lang="less" scoped>
.uploadSimple {
	position: fixed;
	left: 0;
	top: 0;
	width: 100vw;
	height: 100vh;
	overflow: hidden;
	z-index: 9;
}
.camera-preview {
	position: fixed;
	left: -100%;
	bottom: -100%;
}
.camera-capture {
	z-index: 9999999999;
	width: 100vw;
	position: fixed;
	left: 50%;
	transform: translateX(-50%);
	bottom: 10%;
	.cancel {
		position: absolute;
		left: 20%;
		color: #fff;
		font-size: 36px;
	}
	.sure {
		position: absolute;
		left: 70%;
		color: #fff;
		font-size: 36px;
	}
	div {
		margin: 0 10px;
	}
}
/deep/ .van-uploader {
	position: fixed;
	left: -100%;
	bottom: -100%;
}
.customLoading {
	z-index: 99;
	position: absolute !important;
	left: 50%;
	top: 50%;
	transform: translate(-50%, -50%);
}
</style>
